//
//  MTEmailViewController.m
//  YuchBox
//
//  Created by Ivan on 11-10-26.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "MTEmailViewController.h"
#import "Utility.h"
#import "DataSource.h"
#import "LayoutParam.h"
#import "YuchBoxAppDelegate.h"

//
// class table view
//
#pragma mark - MTEmailViewController

#define MAX_EMAILS_LOAD     12

@implementation MTEmailViewController
//@synthesize showViewController   = _showViewController;
@synthesize emails               = _emails;
@synthesize show6ViewController  = _show6ViewController;
@synthesize emailsTotalCount     = _emailsTotalCount;

static NSDictionary *MAIL_STATUS_IMAGE = nil;
static NSInteger    objectRef = 0;

+ (void)mailStatusImageInit
{
    if (!MAIL_STATUS_IMAGE) {
        MAIL_STATUS_IMAGE = [[NSDictionary alloc] initWithObjectsAndKeys:
                             @"mail_list_flag_recv_read.png", [NSNumber numberWithInt:EMAIL_STATUS_RECV_READ],
                             @"mail_list_flag_recv.png", [NSNumber numberWithInt:EMAIL_STATUS_RECV_UNREAD],
                             @"mail_list_flag_recv_read_attach.png", [NSNumber numberWithInt:EMAIL_STATUS_RECV_ATTACH_READ],
                             @"mail_list_flag_recv_attach.png", [NSNumber numberWithInt:EMAIL_STATUS_RECV_ATTACH_UNREAD],
                             @"mail_list_flag_send_sending.png",  [NSNumber numberWithInt:EMAIL_STATUS_SEND_SENDING],
                             @"mail_list_flag_send_sent.png",  [NSNumber numberWithInt:EMAIL_STATUS_SEND_SENT],
                             @"mail_list_flag_send_error.png",  [NSNumber numberWithInt:EMAIL_STATUS_SEND_FAIL],
                             @"mail_list_flag_send_draft.png",  [NSNumber numberWithInt:EMAIL_STATUS_SEND_DRAFT],
                             nil];
    }
}

- (id)init
{
    self = [super init];

    if (self) {
        // Custom initialization
        self.view.frame = CGRectMake(0, 0, 320, DEVICE_HEIGHT - TOOLBAR_HEIGHT - 20);

        TTLOG_INFO(@"email view controller init");
        [MTEmailViewController mailStatusImageInit];
        objectRef ++;
    }

    return self;
}

- (NSInteger)loadEmailsFromDB
{
    NSInteger loadNum = 0; 
    
    _emailsTotalCount   = [Email getEmailTotal:IVAN_DB];
    _emailsUnreadCount  = [Email getEmailUnreadTotal:IVAN_DB];
    
    loadNum = [Email retrieveEmails:IVAN_DB emails:self.emails limit:MAX_EMAILS_LOAD offset:_emailsLoadOffset];
    _emailsLoadOffset += MAX_EMAILS_LOAD;

//    [self eventInvoke:DSEventOpCheckEmailState info:nil];
    return loadNum;
}

- (void)loadMoreEmail
{
    NSInteger loadEmailNum = [self loadEmailsFromDB];
    NSMutableArray *insertIndexPath = [NSMutableArray arrayWithCapacity:loadEmailNum];
    
    for (int i = _emails.count - loadEmailNum; i < _emails.count; i++ ) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        [insertIndexPath addObject:indexPath];
    }
    
    if (0 == insertIndexPath.count) {
        return;
    }
    
    [self.tableView insertRowsAtIndexPaths:insertIndexPath withRowAnimation:UITableViewRowAnimationTop];
    
    [self eventInvoke:DSEventOpCheckEmailState info:nil];
}

- (void)showNewRecvEmail:(NSNumber *)number
{
    Email *email = [Email retrieveEmail:IVAN_DB pkId:[number longLongValue]];
    [_emails insertObject:email atIndex:0];
    
    _emailsTotalCount ++;
    _emailsUnreadCount ++;
    _emailsLoadOffset ++;
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    
    UILocalNotification *notify = [[UILocalNotification alloc] init];
    if (nil != notify) {
        notify.alertBody = email.subject;
        
        [[UIApplication sharedApplication] presentLocalNotificationNow:notify];
    }
    
    [notify release];
    [self eventInvoke:DSEventOpCheckEmailState info:nil];
}

- (void)refreshAction:(id)sender
{
    [self.emails removeAllObjects];
    _emailsLoadOffset = 0;
    [self loadEmailsFromDB];
    [self.tableView reloadData];
}

- (void)setBarItems
{
    MTRootToolBarViewController *rootViewController =  [YuchBoxAppDelegate shareAppDelegate].rootToolBarViewController;
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
//    titleView.backgroundColor = [UIColor blueColor];
    
    UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
    refreshButton.frame = CGRectMake(7, 7, 26, 26);
    [refreshButton addTarget:self action:@selector(refreshAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [refreshButton setBackgroundImage:[UIImage imageNamed:@"bar_reload"] forState:UIControlStateNormal];
    [titleView addSubview:refreshButton];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(140, 0, 60, 40)];
    label.backgroundColor = [UIColor clearColor];

    label.text = @"收件箱";
    label.font = [UIFont boldSystemFontOfSize:16];
    label.textColor = [UIColor whiteColor];
    [titleView addSubview:label];
    [label release];
    
    UIButton *editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    editButton.frame = CGRectMake(270, 7, 26, 26);
    [editButton setBackgroundImage:[UIImage imageNamed:@"bar_edit.png"] forState:UIControlStateNormal];
    [titleView addSubview:editButton];
    
    [rootViewController.navigationItem setTitleView:titleView];
    [titleView release];
//    [rootViewController.navigationController.view setHidden:NO];
    // refresh button
//    UIBarButtonItem *refreshButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"刷新" style:UIBarButtonItemStylePlain target:self action:@selector(refreshAction:)];
    //    refreshButtonItem
//    [rootViewController.navigationItem setLeftBarButtonItem:refreshButtonItem];
    [rootViewController.navigationItem setTitle:@"收件箱"];
//    [refreshButtonItem release];
}

- (void)clearBarItems
{
    MTRootToolBarViewController *rootViewController =  [YuchBoxAppDelegate shareAppDelegate].rootToolBarViewController;
//    [rootViewController.navigationController.view setHidden:YES];
    
    [rootViewController.navigationItem setTitleView:nil];
//    [rootViewController.navigationItem setLeftBarButtonItem:nil];
    [rootViewController.navigationItem setTitle:@""];
}

#pragma View lifecycle
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    TTLOG_INFO(@"view did load");
    _emails = [[NSMutableArray alloc] init];
    // show table
    [self loadEmailsFromDB];
    
    MTEmailShow6ViewController *show6ViewController = [[MTEmailShow6ViewController alloc] init];
    [self setShow6ViewController:show6ViewController];
    [show6ViewController setCurrentDelegate:self];
    [show6ViewController release];
    
    [self eventInvoke:DSEventOpCheckEmailState info:nil];
    
    [self setBarItems];
}

- (void)dealloc
{
    if (--objectRef == 0) {
        [MAIL_STATUS_IMAGE release];
    }
    
    [_emails release];
    [super dealloc];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [_show6ViewController release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

// WARNING call this function in the IvanTabBar by ourself
- (void)viewWillAppear:(BOOL)animated
{

}

- (void)viewDidAppear:(BOOL)animated
{
//    [super viewDidAppear:animated];

}

- (void)viewDidDisappear:(BOOL)animated
{

}

#pragma mark -
#pragma IvanTabBarDelegate
- (void)viewWillAppearIvan:(BOOL)animated
{
    NSLog(@"@@@@ will appearIvan");
    [self setBarItems];
}

- (void)viewDidAppearIvan:(BOOL)animated
{
    [[YuchBoxAppDelegate shareStateViewer] setTemporaryHide:NO delegate:nil];
}

- (void)viewWillDisappearIvan:(BOOL)animated
{
    NSLog(@"@@@@ did disappearIvan");
    [self clearBarItems];
}

#pragma Table view
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  _emails.count + 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == _emails.count) {
        return TABLEVIEW_CELL_LAST_MORE_HEIGHT;
    }
    
    return TABLEVIEW_CELL_HEIGHT;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 10.0f;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return 10.0f;
//}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"accessoryButtonTappedForRowWithIndexPath");
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"commitEditingStyle");
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//    return nil;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    MTEmailShowViewController *emailShowViewController = [[MTEmailShowViewController alloc] initWithNibName:@"MTEmailShowViewController" bundle:nil];

     [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.row < _emails.count) {
        Email *email = [_emails objectAtIndex:indexPath.row];
        [self.show6ViewController loadEmail:email];
//        [self.show6ViewController.navigationItem setTitle:[NSString stringWithFormat:@"%d / %d", indexPath.row + 1, _emails.count]];
        [[YuchBoxAppDelegate shareStateViewer] setTemporaryHide:YES delegate:self];
        UIViewController *viewController = [YuchBoxAppDelegate shareAppDelegate].rootToolBarViewController;
        [viewController.navigationController pushViewController:self.show6ViewController animated:YES];
        
        _selectRow = indexPath.row;
    } else {
        [self loadMoreEmail];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
	static NSString *MyIdentifier = @"MyIdentifier";
	
	// Try to retrieve from the table view a now-unused cell with the given identifier.
	// If no cell is available, create a new one using the given identifier.
    
    // the last cell. <get more date....>
    NSLog(@"%d == %d", indexPath.row, _emails.count);
    if (indexPath.row == _emails.count) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MoreCell"];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:[NSString stringWithFormat:@"MoreCell"]] autorelease];
            UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,
                                                                       TABLEVIEW_CELL_TOP_LEFT_Y + 5.0f, 
                                                                       320.0f, 
                                                                       cell.frame.size.height/2)];
//            leftLabel.backgroundColor   =   [UIColor grayColor];
            [leftLabel setTag:TABLEVIEW_CELL_MORE_TAG];
            leftLabel.font          = [UIFont boldSystemFontOfSize:16];
            leftLabel.textColor     = [UIColor colorWithRed:30.0/255.9 green:145.0/255.0 blue:180.0/255.0 alpha:1.0f];
            leftLabel.textAlignment = UITextAlignmentCenter;
            [cell.contentView addSubview:leftLabel];
            [leftLabel release];
            
            UILabel *rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,
                                                                           TABLEVIEW_CELL_TOP_LEFT_Y + cell.frame.size.height/2 + 5.0f, 
                                                                           320.0f, 
                                                                           cell.frame.size.height/2)];
            [rightLabel setTag:TABLEVIEW_CELL_MORE_DIS_TAG];
            rightLabel.textColor    = [UIColor colorWithRed:53.0/255.9 green:53.0/255.0 blue:53.0/255.0 alpha:1.0f];
            rightLabel.font         = [UIFont systemFontOfSize:12];
            [cell.contentView addSubview:rightLabel];
            [rightLabel release];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        UILabel *leftLabel      = (UILabel *)[cell.contentView viewWithTag:TABLEVIEW_CELL_MORE_TAG];
        leftLabel.text          = @"加载更多邮件...";
        
        UILabel *rightLabel     = (UILabel *)[cell.contentView viewWithTag:TABLEVIEW_CELL_MORE_DIS_TAG];
        rightLabel.text         = [NSString stringWithFormat:@"共%d封邮件，已加载%d封，未读%d封", _emailsTotalCount, _emails.count, _emailsUnreadCount];
        rightLabel.textAlignment = UITextAlignmentCenter;
        
        return cell;
    }
    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    // email cell;
	if (cell == nil) {
		// Use the default cell style.
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier] autorelease];
        UILabel *topLeft   = [[UILabel alloc] initWithFrame:CGRectMake(TABLEVIEW_CELL_TOP_LEFT_X, 
                                                                       TABLEVIEW_CELL_TOP_LEFT_Y, 
                                                                       TABLEVIEW_CELL_TOP_LEFT_WIDTH, 
                                                                       TABLEVIEW_CELL_TOP_HEIGHT)];
        
        UIImageView *topMiddle  = [[UIImageView alloc] initWithFrame:CGRectMake(TABLEVIEW_CELL_TOP_MIDDLE_X,
                                                                        TABLEVIEW_CELL_TOP_MIDDLE_Y, 
                                                                        TABLEVIEW_CELL_TOP_MIDDLE_WIDTH,
                                                                        TABLEVIEW_CELL_TOP_HEIGHT)];
        
        UILabel *topRight  = [[UILabel alloc] initWithFrame:CGRectMake(TABLEVIEW_CELL_TOP_RIGHT_X,
                                                                       TABLEVIEW_CELL_TOP_RIGHT_Y, 
                                                                       TABLEVIEW_CELL_TOP_RIGHT_WIDTH,
                                                                       TABLEVIEW_CELL_TOP_HEIGHT)];
        
        UILabel *middle    = [[UILabel alloc] initWithFrame:CGRectMake(TABLEVIEW_CELL_MIDDLE_X,
                                                                       TABLEVIEW_CELL_MIDDLE_Y, 
                                                                       TABLEVIEW_CELL_MIDDLE_WIDTH,
                                                                       TABLEVIEW_CELL_MIDDLE_HEIGHT)];
        
        UILabel *bottom    = [[UILabel alloc] initWithFrame:CGRectMake(TABLEVIEW_CELL_BOTTOM_X,
                                                                       TABLEVIEW_CELL_BOTTOM_Y,
                                                                       TABLEVIEW_CELL_BOTTOM_WIDTH,
                                                                       TABLEVIEW_CELL_BOTTOM_HEIGHT)];
        topRight.textColor = [UIColor colorWithRed:30.0/255.9 green:145.0/255.0 blue:180.0/255.0 alpha:1.0f];
        
        
       
        [topLeft setTag:TABLEVIEW_CELL_TOP_LEFT_TAG];
        [topLeft setFont:[UIFont systemFontOfSize:12]];
        [topLeft setTextColor:[UIColor grayColor]];
         
        [topMiddle setTag:TABLEVIEW_CELL_TOP_MIDDLE_TAG];
        
        [topRight setTag:TABLEVIEW_CELL_TOP_RIGHT_TAG];
        [topRight setFont:[UIFont systemFontOfSize:[UIFont smallSystemFontSize]]];
        [topRight setAutoresizingMask:UIViewAutoresizingFlexibleWidth];

        [middle setFont:[UIFont systemFontOfSize:14]];
        [middle setTag:TABLEVIEW_CELL_MIDDLE_TAG];
        [middle setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
        
        [bottom setTag:TABLEVIEW_CELL_BOTTOM_TAG];
        [bottom setFont:[UIFont systemFontOfSize:[UIFont smallSystemFontSize]]];
        [bottom setTextColor:[UIColor grayColor]];
        [bottom setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
        
        [cell.contentView addSubview:topLeft];
        [cell.contentView addSubview:topMiddle];
        [cell.contentView addSubview:topRight];
        [cell.contentView addSubview:middle];
        [cell.contentView addSubview:bottom];
        //[cell setAccessoryView:cellLable];
        [topLeft release];
        [topMiddle release];
        [topRight release];
        [middle release];
        [bottom release];
        
//        cell setSelectionStyle:UITableViewCellSelectionStyleGray;
	}
    
    UILabel *topLeft    = (UILabel *)[cell.contentView viewWithTag:TABLEVIEW_CELL_TOP_LEFT_TAG];
    UIImageView *topMiddle = (UIImageView *)[cell.contentView viewWithTag:TABLEVIEW_CELL_TOP_MIDDLE_TAG];
    UILabel *topRight   = (UILabel *)[cell.contentView viewWithTag:TABLEVIEW_CELL_TOP_RIGHT_TAG];
    UILabel *middle     = (UILabel *)[cell.contentView viewWithTag:TABLEVIEW_CELL_MIDDLE_TAG];
    UILabel *bottom     = (UILabel *)[cell.contentView viewWithTag:TABLEVIEW_CELL_BOTTOM_TAG];

//    topLeft.backgroundColor = [UIColor grayColor];
//    [topMiddle setBackgroundColor:[UIColor blueColor]];
//    topRight.backgroundColor = [UIColor redColor];
//    middle.backgroundColor = [UIColor greenColor];
//    bottom.backgroundColor = [UIColor yellowColor];
    
    Email *email  = [_emails objectAtIndex:indexPath.row];
    
//    NSRange range = [email.fromString rangeOfString:@"<"];

//    NSString *tempText = range.length != 0 ? [email.fromString substringToIndex:range.location] : email.fromString;
    
    topLeft.text = [NSString stringWithFormat:@"From: %@", email.fromString];
    
    UIImage * mailStatus = [UIImage imageNamed:[MAIL_STATUS_IMAGE objectForKey:[NSNumber numberWithInt:email.status]]];
    [topMiddle setImage:mailStatus];
//    topMiddle.contentMode = UIViewContentModeCenter;

    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
    [dateformat setDateFormat:@"yy-MM-dd"];
    topRight.text = [dateformat stringFromDate:email.sendDate];
    topRight.textAlignment = UITextAlignmentRight;
    [dateformat release];
    
    middle.text = email.subject.length == 0 ? @"(空)" : email.subject;
    
    bottom.numberOfLines = 2;
    bottom.text          = [UTIL_TRIM(email.content) length] == 0 ? @"(空)"  : email.content;

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSLog(@"return cell for row at index path:%d, email index:%llu", indexPath.row, email.uid);

//     [tableView deselectRowAtIndexPath:indexPath animated:NO];
	return cell;
}

#pragma mark - 
#pragma StateViewerDelegate

- (void)stateViewerSetup:(StateViewer *)stateViewer
{
    //[self.navigationController.navigationBar addSubview:stateViewer];
    //stateViewer.alpha = 0.0f;
}

- (void)stateViewerUnsetup:(StateViewer *)stateViewer
{
    //stateViewer.alpha = 0.1f;
    //[stateViewer removeFromSuperview];
}

//#pragma mark -
//#pragma MTEmailShow6Delegate
//- (void)callback:(NSInteger)callbackType param:(id)param
//{
//    switch (callbackType) {
//        case CALLBACK_CHANGE_ICON: {
//            [self eventInvoke:DSEventOpEmailRead info:param];
////            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_selectRow inSection:0];
////            UIImageView *topMiddle = (UIImageView *)[[self.tableView cellForRowAtIndexPath:indexPath] viewWithTag:TABLEVIEW_CELL_TOP_MIDDLE_TAG];
////            
////            NSNumber *emailStatusNumber = (NSNumber *)param;
////            [topMiddle setImage:[UIImage imageNamed:[MAIL_STATUS_IMAGE objectForKey:[NSNumber numberWithInt:[emailStatusNumber intValue]]]]];
//            break;
//        }
//        default:
//            break;
//    }
//}

#pragma mark - 
#pragma event handle
- (void)eventInvoke:(DataSourceEvent)eventCode info:(id)info
{
    switch (eventCode) {
        case DSEventSBRecvMessage: {
//            [[YuchBoxAppDelegate shareStateViewer] setState:StateEventOnlineNewMsg animated:YES delegate:nil];
            [self performSelectorOnMainThread:@selector(showNewRecvEmail:) withObject:info waitUntilDone:NO];
            break;
        }
        case DSEventOpEmailRead: {
            // change the email image to read from unread
            Email *email = (Email *)info;
            [email chagneStatusToRead:IVAN_DB];
            NSInteger emailIndex = [_emails indexOfObject:email];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:emailIndex inSection:0];
            UIImageView *topMiddle = (UIImageView *)[[self.tableView cellForRowAtIndexPath:indexPath] viewWithTag:TABLEVIEW_CELL_TOP_MIDDLE_TAG];
            [topMiddle setImage:[UIImage imageNamed:[MAIL_STATUS_IMAGE objectForKey:[NSNumber numberWithInt:email.status]]]];
            
            _emailsUnreadCount --;
            [self eventInvoke:DSEventOpCheckEmailState info:nil];
            
            break;
        }
        case DSEventOpCheckEmailState: {
            if (_emailsUnreadCount != 0) {
                [[YuchBoxAppDelegate shareStateViewer] setStateMessage:StateMessageNewMessage];
            } else {
                [[YuchBoxAppDelegate shareStateViewer] setStateMessage:StateMessageNoNewMessage];            
            }
            
            // refresh last cell
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_emails.count inSection:0];
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
        default:
            break;
    }
}
@end

//@implementation MTEMailNavigationBar
//
//@synthesize currentDelegate = _currentDelegate;
//
//- (id)initWithFrame:(CGRect)frame
//{
//    self = [super initWithFrame:frame];i
//    //MTEMailNavigationBar *navbar = [[MTEMailNavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, NAVIGATION_BAR_HIGHT)];
//    //[navbar setBackgroundImage:[UIImage imageNamed:@"emailNavbarBackgroud.png"] forBarMetrics:UIBarMetricsDefault];
//    //navbar.tintColor = [UIColor whiteColor];
//    //navbar.frame = [UIColor blackColor]; 
//    //return;
//    UINavigationItem * titleItem = [[UINavigationItem alloc] init];
//    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
//    titleLable.textColor        = [UIColor blackColor];
//    titleLable.backgroundColor  = [UIColor clearColor];
//    titleLable.textAlignment    = UITextAlignmentCenter;
//    titleLable.text             = @"Gmail";
//    //return;
//    //UIView *board = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 45)];
//    //board.backgroundColor = [UIColor blueColor];
//    titleItem.titleView = titleLable;
//    //titleItem.titleView = board;
//    //[board addSubview:titleLable];
//    //[titleItem.titleView addSubview:titleLable];
//    //[navbar addSubview:titleLable];
//    [titleLable release];
//    UIButton * leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
//    [leftButton setBackgroundImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
//    [leftButton addTarget:_currentDelegate action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
////    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
////    leftButton.frame = CGRectMake(0, 0, 32, 32);
////    [leftButton setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
//    leftButton.adjustsImageWhenHighlighted = NO;
//    UIBarButtonItem  *leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
//
//    [leftButton release];
//    
//    UIButton * rightButton = [[UIButton  alloc] initWithFrame:CGRectMake(260, 0, 32, 32)];
//    [rightButton setBackgroundImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
//    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
//    
//    [rightButton release];
//    //UINavigationItem * back = [[UINavigationItem alloc] initWithTitle:@"back"];
//    //UIBarButtonItem  *newBackButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:nil action:nil];
//    
//    //newBackButton.enabled = YES;
//    //newBackButton.style = UIBarButtonItemStylePlain;
//    //newBackButton.width = 10;
//    
//    titleItem.rightBarButtonItem = rightButtonItem;
//    titleItem.leftBarButtonItem  = leftButtonItem;
//    
//    [leftButtonItem release];
//    [rightButtonItem release];
//    
//    //UIImageView *editImage = [[UIImageView alloc] initWithFrame:CGRectMake(260, 0, 32, 32)];
//    //editImage.image = [UIImage imageNamed:@"edit.png"];
//    
//    //titleItem.leftBarButtonItem.tintColor = [UIColor blueColor];
//    //titleItem.leftBarButtonItem.image = [UIImage imageNamed:@"edit.png"];
//    //titleItem.titleView = editImage;
//    //[navbar addSubview:editImage];
//    //[titleItem.leftBarButtonItem setCustomView:editImage];
//    //titleItem.leftBarButtonItem
//    //[titleItem.titleView addSubview:editImage];
//    //UIButton * backButton = [[UIButton alloc] initWithFrame:CGRectMake(260, 0, 32, 32)];
//    //[backButton setBackgroundImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
//    
//    
//    
//    //back.titleView = newBackButton;
//    //initWithImage:[UIImage imageNamed:@"edit.png"] style:UIBar target:nil action:nil]; 
//    ///    [newBackButton setTintColor:[UIColor whiteColor]];
//    //    [newBackButton setWidth:20];
//    //initWithTitle:@"new back" style:UIBarButtonItemStylePlain target:nil action:nil];
//    //newBackButton setBackgroundImage:(UIImage *) forState:(UIControlState) barMetrics:(UIBarMetrics)
//    // [back setBackBarButtonItem:newBackButton];
//    //   NSArray *rightItems = [[NSArray alloc] initWithObjects:leftButtonItem, nil];
//    //    [back setLeftBarButtonItems:rightItems];
//    
//    //    back.leftBarButtonItem = leftButtonItem;
//    
//    NSArray *items = [[NSArray alloc] initWithObjects:titleItem, nil];
//    [self setItems:items];
//    //[self.view addSubview:navbar];
//    [titleItem release];
//    [items release];
////    [navbar release];
//    
//    return self;
//}
//
//- (void)drawRect:(CGRect)rect
//{
//    UIImage *image = [UIImage imageNamed:@"emailNavbarBackgroud.png"];
//    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
// //   NSLog(@"???");
//}
//@end
